/**
 * Copyright (c) 2015-2016, Javen Zhou  (javenlife@126.com).
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.aef.controller;

import com.aef.model.TdWeixinUsers;
import com.aef.service.WeixinUserService;
import com.aef.utils.DateUtils;
import com.aef.utils.MapUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.http.demo.Method;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.MenuApi;
import com.jfinal.weixin.sdk.api.RedPackApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.*;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutCustomMsg;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.jfinal.weixin.sdk.msg.out.TransInfo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import com.http.test.TestCase;


public class WeixinMsgController extends MsgControllerAdapter {
	public static String domain = PropKit.get("domain");
	private static final String helpStr =PropKit.get("helpStr"); ;
	static String vipKF=PropKit.get("vipKF");
	static Log logger = Log.getLog(WeixinMsgController.class);
	public static String SERVICE_OPENID = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=TOKEN";
	// 新增OpenId
	private static final String insertOpenIdurl="http://118.178.18.0:8082/alfa-mobile-ws/rest/OpenId/insertOpenId";
	//private static final String insertOpenIdurl="http://120.27.192.10/alfa-mobile-ws/rest/OpenId/insertOpenId";
	//更新openid
	private static final String updateOpenIdurl="http://118.178.18.0:8082/alfa-mobile-ws/rest/OpenId/updateOpenId";
	//private static final String updateOpenIdurl="http://120.27.192.10/alfa-mobile-ws/rest/OpenId/updateOpenId";
	WeixinUserService weixinUserService=new WeixinUserService();

	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
	 * ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();

		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));

		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}

	/**
	 * 实现父类抽方法，处理文本消息 本例子中根据消息中的不同文本内容分别做出了不同的响应，同时也是为了测试 jfinal weixin
	 * sdk的基本功能： 本方法仅测试了 OutTextMsg、OutNewsMsg、OutMusicMsg 三种类型的OutMsg，
	 * 其它类型的消息会在随后的方法中进行测试
	 */
	protected void processInTextMsg(InTextMsg inTextMsg) {
		 String msgContent = inTextMsg.getContent().trim();
	        // 帮助提示
	        if ("help".equalsIgnoreCase(msgContent) || "帮助".equals(msgContent)) {
	        	OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent("客户电话:02365671390");
				render(outMsg);
	        }else {
	        	OutTextMsg outMsg = new OutTextMsg(inTextMsg);
				outMsg.setContent("测试");
				render(outMsg);
	        }
		/*forwardMsg(inTextMsg);*/
	}

	/**
	 * 实现父类抽方法，处理图片消息
	 */
	protected void processInImageMsg(InImageMsg inImageMsg) {
		forwardMsg(inImageMsg);
	}

	/**
	 * 实现父类抽方法，处理语音消息
	 */
	protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
		forwardMsg(inVoiceMsg);
	}

	/**
	 * 实现父类抽方法，处理视频消息
	 */
	protected void processInVideoMsg(InVideoMsg inVideoMsg) {
		forwardMsg(inVideoMsg);
	}

	@Override
	protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
		forwardMsg(inShortVideoMsg);
	}


	@Override
	protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
		renderOutTextMsg(helpStr);
	}

	@Override
	protected void processInLocationEvent(InLocationEvent inLocationEvent) {
		renderNull();
	}

	@Override
	protected void processInMassEvent(InMassEvent inMassEvent) {
		renderNull();
	}

	/**
	 * 实现父类抽方法，处理自定义菜单事件
	 */
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		String eventKey = inMenuEvent.getEventKey();
		if (eventKey.equals("11")) {
			OutNewsMsg outMsg = new OutNewsMsg(inMenuEvent);
			outMsg.addNews("油微网", "油微网", "https://mmbiz.qlogo.cn/mmbiz/ibHRiaZ9MRcUosol56OtHjVibWTK9opiaxsY9tPDricojmV5xxuLJyibZJXMAdNOx1qbZFcic9SvsPF2fTUnSc9oQB1IQ/0?wx_fmt=jpeg","http://www.baidu.com");
			render(outMsg);
		}else if(eventKey.equals("joinus")){
			OutNewsMsg outMsg = new OutNewsMsg(inMenuEvent);
			outMsg.addNews("加入我们", "加入我们", "https://mmbiz.qlogo.cn/mmbiz/ibHRiaZ9MRcUosol56OtHjVibWTK9opiaxsY9tPDricojmV5xxuLJyibZJXMAdNOx1qbZFcic9SvsPF2fTUnSc9oQB1IQ/0?wx_fmt=jpeg","http://www.baidu.com");
			render(outMsg);
		}else if(eventKey.equals("Professional")){
			OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
			outMsg.setContent("客户电话:02365671390");
			render(outMsg);
		}
	}

	@Override
	protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
		renderNull();
	}

	/**
	 * 实现父类抽方法，处理链接消息 特别注意：测试时需要发送我的收藏中的曾经收藏过的图文消息，直接发送链接地址会当做文本消息来发送
	 */
	protected void processInLinkMsg(InLinkMsg inLinkMsg) {
		renderNull();
	}

	/**
	 * 客服事件
	 * @param inCustomEvent
	 */
	@Override
	protected void processInCustomEvent(InCustomEvent inCustomEvent) {
		  renderOutTextMsg("\t文本消息已成功接收，内容为：\n\n" + helpStr);
	}

	/**
	 * 实现父类抽方法，处理关注/取消关注消息
	 */
	protected void processInFollowEvent(InFollowEvent inFollowEvent) {
		JSONObject userjson=new JSONObject();
		userjson=JSONObject.parseObject(UserApi.getUserInfo(inFollowEvent.getFromUserName()).getJson());
		TdWeixinUsers user=new TdWeixinUsers();
		WeixinApiController weixinApiController=new WeixinApiController();
		weixinApiController.createMenu();
		if(inFollowEvent.getEvent().equals("subscribe")){
			Map<String, String> bodyParam=new HashMap<String,String>();
			bodyParam.put("openid", userjson.getString("openid"));
			bodyParam.put("headimgurl", userjson.getString("headimgurl"));
			bodyParam.put("nickname", userjson.getString("nickname"));
			bodyParam.put("state", "0");
			String json = JSONObject.toJSONString(bodyParam); 
			System.out.println(json);
			TestCase.post(json,insertOpenIdurl);
			OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
			outMsg.setContent(helpStr);
			render(outMsg);
		}else{
			Map<String, String> bodyParam=new HashMap<String,String>();
			bodyParam.put("openid", userjson.getString("openid"));
			bodyParam.put("state", "1");
			String json = JSONObject.toJSONString(bodyParam); 
			System.out.println(json);
			TestCase.post(json,updateOpenIdurl);
		}
	}

	/**
	 * 处理接收到的模板消息是否送达成功通知事件
	 * @param inTemplateMsgEvent
	 */
	protected void processInTemplateMsgEvent(InTemplateMsgEvent inTemplateMsgEvent) {
		renderNull();
	}

	@Override
	protected void processInShakearoundUserShakeEvent(InShakearoundUserShakeEvent inShakearoundUserShakeEvent) {
		renderNull();
	}

	@Override
	protected void processInVerifySuccessEvent(InVerifySuccessEvent inVerifySuccessEvent) {
		renderNull();
	}

	@Override
	protected void processInVerifyFailEvent(InVerifyFailEvent inVerifyFailEvent) {
		renderNull();
	}

	private void forwardMsg(InMsg inMsg){
	}
	public String Servicepost(String action, String json) {
		HttpURLConnection http = null;
		try {
			URL url = new URL(action);
			http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(json.getBytes("UTF-8"));// 传入参数
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String result = new String(jsonBytes, "UTF-8");
			System.out.println("请求返回结果:" + result);
			os.flush();
			os.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (http != null) {
				http.disconnect();
			}
		}
		return null;

	}
	public String TextToUser(String content, String toUser,String token){
		String json = "{\"touser\": \"" + toUser
				+ "\",\"msgtype\": \"text\", \"text\": {\"content\": \""
				+ content + "\"}}";
		// 获取请求路径
		String action = SERVICE_OPENID.replace("TOKEN", token);
		try {
			return Servicepost(action, json);
		} catch (Exception e) {

			e.printStackTrace();
		}
		return null;

	}

}
